/** @file    ThreadManager.cpp
 *  @author  Alessandro Polo
 *  @version $Id: ThreadManager.cpp 2832 2010-08-02 22:53:46Z alex $
 *  @brief
 * File containing methods for the wosh::ThreadManager class.
 * The header for this class can be found in ThreadManager.h, check that file
 * for class description.
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/
 
 #include <core/ThreadManager.h>
 #include <core/ObjectAllocator.h>
 #include <core/WoshKernel.h>
 #include <core/SystemError.h>
 #include <core/MethodsCommon.h>
 #include <core/Table.h>
 #include <core/List.h>
 #include <core/Functional.h>
 #include <core/Utilities.h>
 #include <core/DataModels.h>


using namespace std;
namespace wosh {

/**
 * @class   wosh::ThreadManagerMonitor
 * @brief   Helper class, iterative check threads..
 *
 *
 ****************************************************************************
 * @author  Alessandro Polo
 ****************************************************************************/
class ThreadManagerMonitor : public ThreadImpl
 {
	WOSH_CLASSNAME(wosh::ThreadManagerMonitor)
	WOSH_CLASS_ABSTRACT(false)

	public:
		ThreadManagerMonitor( ThreadManager* Parent )
			: ThreadImpl(Parent, "ThreadManager.ThreadManagerMonitor"), parent(Parent) {
			this->aliveVariance = 5000;
		 }
		virtual ~ThreadManagerMonitor() { }

	public:
		bool initializeThread() {
			if ( this->parent == NULL ) return false;
			return true;
		 }
		void runThread() {
			while(this->running) {
				if ( !waitForMSec(1000) )
					break;
				this->parent->threads.transactionBeginRead();
				ThreadManager::tThreadList::ConstIterator it;
				const ThreadManager::tThreadList::ConstIterator it_end = this->parent->threads.end();
				for ( it=this->parent->threads.begin(); it!=it_end; ++it ) {
					if ( !this->running ) break;
					if ( *it == NULL || *it == this ) continue;
					if ( (*it)->getThreadAliveTs() == -1 ) continue; // feature not enabled
					if ( !(*it)->isThreadRunning() ) continue; // nothing to check within stopped threads
					if ( (*it)->isThreadAlive() ) continue; // claims to be alive! (for sure it was -variance- seconds ago)

					SystemError::raise(this->parent, this->parent->Log, SystemError::WARNING, _ThreadManager_ERROR_dead_thread, "ThreadMonitor",
						"Thread #%ld [%s]: seems Dead (last alive at %ld)", (*it)->getThreadID(), (*it)->getThreadName().c_str(), (*it)->getThreadAliveTs() );
					///@bug this will flood!

					(*it)->crashDetected( -1.0 );
					// sure about this: ?
					(*it)->setThreadState( Thread::STATE_CRASHED, false );
				 }
				this->parent->threads.transactionEnd();
			 }
		 }

	private:
		ThreadManager* parent;
};

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Meyer singleton! static reference is allocated on first user, detroyed by kernel
extern "C" {
	ThreadManager& ThreadManager::getInstance() { 
		static ThreadManager* ans = new ThreadManager( WoshKernel::getInstance() );
		return *ans;
	}
}
 // register as abstract because it is a singleton:
 WOSH_REGISTER_INTERFACE(wosh::ThreadManager, "wosh::WoshModule", 0.01, _static_ThreadManager )

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////// CONSTRUCTORS

ThreadManager::ThreadManager( const WoshKernel* parent )
	: WoshModule(parent, _ThreadManager_NAME, _ThreadManager_URI) {
	this->monitor = NULL;

	Log(LOG_DEBUG, " Initializing Properties.." );
	Properties.set( _ThreadManager_KEY_Count,			0, Permission( Permission::Read ) );
	Properties.set( _ThreadManager_KEY_ThreadMonitor,	false, Permission::RW_R__R__() );
	Properties.monitor(_ThreadManager_KEY_ThreadMonitor);

	Log(LOG_DEBUG, " Registering Methods.." );
	MethodRequest* mmStartThread = Methods.create<MethodRequest>( _ThreadManager_METHOD_start, "Start Thread", Permission::R_XR__R__() );
	mmStartThread->setMethod( this, (MethodRequestPtr)&ThreadManager::mmDoStartThread );

	MethodRequest* mmStopThread = Methods.create<MethodRequest>( _ThreadManager_METHOD_stop, "Stop Thread", Permission::R_XR__R__() );
	mmStopThread->setMethod( this, (MethodRequestPtr)&ThreadManager::mmDoStopThread );

	MethodRequest* mmTerminateThread = Methods.create<MethodRequest>( _ThreadManager_METHOD_terminate, "Terminate Thread", Permission::R_XR__R__() );
	mmTerminateThread->setMethod( this, (MethodRequestPtr)&ThreadManager::mmDoTerminateThread );

	MethodList* mmListThreads = Methods.create<MethodList>( _METHOD_List, "List Threads", Permission::R_XR_XR__() );
	mmListThreads->setDataFieldExtractor( DataFieldExtractor<Thread>::createFor< DataAdapterListT<Thread> >(this->threads, "Threads") );
 }

ThreadManager::~ThreadManager() {
	Log(LOG_DEBUG, ":~ThreadManager() Destroying.." );
	if ( this->monitor != NULL ) {
		Log(LOG_VERBOSE, ":~ThreadManager() : Destroying ThreadMonitor.." );
		this->monitor->quitThread();
		delete this->monitor; this->monitor = NULL;
		Log(LOG_DEBUG, ":~ThreadManager() : Destroyed ThreadMonitor." );
	 }
	int runnings = countRunning();
	Log(LOG_INFO, " Destroying [count: %d, running %d]..", this->threads.count(), runnings );
	if ( runnings > 0 ) {
		Log(LOG_WARNING, ":~ThreadManager() : Stopping %d Threads", runnings );
		stopThreads( 30000 );
	 }
	if ( this->threads.count() > 0 ) {
		this->threads.transactionBeginRead();
		tThreadList::ConstIterator it;
		const tThreadList::ConstIterator it_end = this->threads.end();
		for ( it=this->threads.begin(); it!=it_end; ++it ) {
			if ( *it == NULL ) continue;
			Log(LOG_WARNING, ":~ThreadManager() (Still registered) Thread#%ld [%s] (%s)", (*it)->getThreadID(), (*it)->getThreadName().c_str(), (*it)->getThreadStateAsString() );
		 }
		this->threads.transactionEnd();
	 }
	else
		Log(LOG_VERBOSE, ":~ThreadManager() : No running Threads" );
	Log(LOG_VERBOSE, " Destroyed." );
 }

//////////////////////////////////////////////////////////////////////////////////////////////// CONSTRUCTORS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////// KERNEL EVENTS

WRESULT ThreadManager::onKernelInitializing() {
	WRESULT ret = WoshModule::onKernelInitializing();

	if ( Properties.exists(_ThreadManager_KEY_ThreadMonitor) ) {
		bool startMonitor = Properties.getValueOf(_ThreadManager_KEY_ThreadMonitor).toBoolean(false);
		if ( startMonitor ) {
			if ( this->monitor == NULL )
				this->monitor = new ThreadManagerMonitor(this);
			Log(LOG_INFO, ":init() : Starting Thread Monitor.." );
			this->monitor->startThread( 5000 ); // synch 5 secs
		 }
	 }
	return ret;
 }

/////////////////////////////////////////////////////////////////////////////////////////////// KERNEL EVENTS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////// PROPERTY EVENTs

bool ThreadManager::updatingProperty( bool& do_update, const Variant& value_proposed, Property& property_current, const PropertiesProvider* source ) {
	if ( property_current.getKey() == _ThreadManager_KEY_ThreadMonitor ) {
		if ( this->initState >= 1 )
			return true;
		if ( value_proposed.toBoolean(false) ) {
			if ( this->monitor == NULL )
				this->monitor = new ThreadManagerMonitor(this);
			if ( !this->monitor->isThreadRunning() ) {
				Log(LOG_INFO, " : Starting Thread Monitor (asynch).." );
				this->monitor->startThread(0); // asynch
			 }
		 }
		else {
			if ( this->monitor == NULL || !this->monitor->isThreadRunning() )
				return true;
			Log(LOG_INFO, " : Stopping Thread Monitor (asynch).." );
			this->monitor->quitThread(0); // asynch
		 }
		return true;
	 }
	// forward processing to base class
	return WoshModule::updatingProperty(do_update, value_proposed, property_current, source);
 }

///////////////////////////////////////////////////////////////////////////////////////////// PROPERTY EVENTs
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////// COLLECTOR METHODS

WRESULT ThreadManager::registerThread_( Thread* thread ) {
	if ( thread == NULL ) return WRET_ERR_PARAM;
	tThreadList::ConstIterator it;
	const tThreadList::ConstIterator it_end = this->threads.end();
	for ( it=this->threads.begin(); it!=it_end; ++it ) {
		if ( *it == NULL ) continue;
		if ( *it != thread ) continue;
		Log(LOG_WARNING, ":registerThread() : Already registered #%ld [%s] (%s)", thread->getThreadID(), thread->getThreadName().c_str(), thread->getThreadStateAsString() );
		return WRET_ERR_PARAM;
	 }
	Log(LOG_INFO, ":registerThread() : Registered %s (%s,%ld)", thread->getThreadName().c_str(), thread->getThreadStateAsString(), thread->getThreadID() );
	this->threads.push_back(thread);
	return WRET_OK;
 }

WRESULT ThreadManager::unRegisterThread_( Thread* thread ) {
	if ( thread == NULL ) return WRET_ERR_PARAM;

	bool found = this->threads.pop(thread);
	if ( !found ) {
		Log(LOG_WARNING, ":unRegisterThread() : Not found #%ld [%s] (%s)", thread->getThreadID(), thread->getThreadName().c_str(), thread->getThreadStateAsString() );
		return WRET_ERR_PARAM;
	 }
	Log(LOG_INFO, ":unRegisterThread() : UnRegistered #%ld [%s] (%s)", thread->getThreadID(), thread->getThreadName().c_str(), thread->getThreadStateAsString() );
	return WRET_OK;
 }

/////////////////////////////////////////////////////////////////////////////////////////// COLLECTOR METHODS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////// THREADs OPERATIONS

WRESULT ThreadManager::stopThreads( unsigned long timeout ) {
	MutexLockerWrite mL(this->threads.getMutex());
	int runnings = countRunning_();
	if ( runnings == 0 ) return WRET_OK;
	if ( timeout != 0 )
		Log(LOG_VERBOSE, ":stopThreads() : Stopping (synch) %d of %d threads..", runnings, this->threads.size() );
	else
		Log(LOG_WARNING, ":stopThreads() : Stopping (Asynch) %d of %d threads..", runnings, this->threads.size() );
	WRESULT ret = WRET_OK;
	int stopped = 0;
	tThreadList::ConstIterator it;
	const tThreadList::ConstIterator it_end = this->threads.end();
	for ( it=this->threads.begin(); it!=it_end; ++it ) {
		Thread* currThread = *it;
		if ( currThread == NULL ) continue;
		if ( currThread == this->monitor ) continue;
		if ( !currThread->isThreadRunning() ) continue;

		currThread->quitThread();
		if ( timeout != 0 ) {
			Log(LOG_VERBOSE, ":stopThreads() : Waiting thread#%ld to stop [%s]", currThread->getThreadID(), currThread->getThreadName().c_str() );
			ret += currThread->waitThread( timeout );
			if ( currThread->isThreadRunning() ) {
				Log(LOG_WARNING, ":stopThreads() : Can't stop thread#%ld [%s]", currThread->getThreadID(), currThread->getThreadName().c_str() );
				SystemError::raise(this,SystemError::CRITICAL,_ThreadManager_ERROR_stop_failure,"stopThreads", &Log);
			 }
			else
				stopped++;
		 }
	 }
	if ( stopped != runnings )
		Log(LOG_WARNING, ":stopThreads() : Stopped %d of %d running threads..", stopped, runnings );
	Log(LOG_INFO, ":stopThreads() : All Threads Stopped [%d]", stopped );
	return ret;
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

int ThreadManager::countRunning() const {
	MutexLockerRead mL(this->threads.getMutex());
	return countRunning_();
 }

int ThreadManager::countRunning_() const {
	int ret = 0;
	tThreadList::ConstIterator it;
	const tThreadList::ConstIterator it_end = this->threads.end();
	for ( it=this->threads.begin(); it!=it_end; ++it ) {
		if ( *it == NULL ) continue;
		if ( (*it)->isThreadRunning() )
			++ret;
	 }
	return ret;
 }

////////////////////////////////////////////////////////////////////////////////////////// THREADs OPERATIONS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////// THREAD EVENTS

void ThreadManager::thread_event( Thread::THREAD_STATE thread_event, Thread* thread ) {
	if ( thread == NULL ) return;
	switch(thread_event) {
		case Thread::STATE_CREATED: {
			// note: Thread ID is assigned when thread is started (now it's 0);
			// WARNING this is called in CONSTRUCTOR, also threadname may be empty!
			// indeed any virtual function on wosh::Thread is INACCESSIBLE
			this->threads.transactionBeginWrite();
			registerThread_( thread );
			this->threads.transactionEnd();
			break;
		 }
		case Thread::STATE_STARTING: {
			// note: Thread ID is assigned when thread is started (now it's 0);
			Log(LOG_VERBOSE, " Thread Starting.. ID: %ld [%s]", thread->getThreadID(), thread->getThreadName().c_str() );
			break;
		 }
		case Thread::STATE_RUNNING: {
			Log(LOG_VERBOSE, " Thread Started! ID: %ld [%s]", thread->getThreadID(), thread->getThreadName().c_str() );
			break;
		 }
		case Thread::STATE_STOPPING: {
			Log(LOG_VERBOSE, " Thread Stopping.. ID: %ld [%s]", thread->getThreadID(), thread->getThreadName().c_str() );
			break;
		 }
		case Thread::STATE_STOPPED: {
			Log(LOG_VERBOSE, " Thread Stopped ID: %ld [%s]", thread->getThreadID(), thread->getThreadName().c_str() );
			break;
		 }
		case Thread::STATE_DESTROYED: {
			unRegisterThread_( thread );
			break;
		 }
		case Thread::STATE_FAILURE: {
			Log(LOG_VERBOSE, " Thread FAILURE ID: %ld [%s]", thread->getThreadID(), thread->getThreadName().c_str() );
			break;
		 }
		case Thread::STATE_CRASHED: {
			Log(LOG_VERBOSE, " Thread CRASHED ID: %ld [%s]", thread->getThreadID(), thread->getThreadName().c_str() );
			break;
		 }
		default: {
			Log(LOG_WARNING, ":thread_event() : Unhandled Event #%d by %ld [%s]", (int)thread_event, thread->getThreadID(), thread->getThreadName().c_str() );
			break;
		 }
	 }
 }

/////////////////////////////////////////////////////////////////////////////////////////////// THREAD EVENTS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////// METHODS

Response* ThreadManager::mmDoStartThread( const Request* request ) {
	if ( request == NULL ) return NULL;
	long tid = 0;
	string name = "";
	if ( request->getArgument().isNumeric() ) {
		tid = request->getArgument().toLong(0);
		Log(LOG_VERBOSE, ":mmDoStartThread(%d)", tid );
	 }
	else if ( request->getArgument().isStringNotEmpty() ) {
		name = request->getArgument().toString();
		Log(LOG_VERBOSE, ":mmDoStartThread(%s)", name.c_str() );
	 }
	else
		return request->replyResponse(WRET_ERR_PARAM, "name or id expected");

	this->threads.transactionBeginRead();
	tThreadList::ConstIterator it;
	const tThreadList::ConstIterator it_end = this->threads.end();
	for ( it=this->threads.begin(); it!=it_end; ++it ) {
		if ( *it == NULL ) continue;
		if ( (*it)->getThreadID() == tid || (*it)->getThreadName() == name ) {
			if ( (*it)->isThreadRunning() ) {
				this->threads.transactionEnd();
				return request->replyResponse(WRET_ERR_ILLEGAL_USE, "Already Running!");
			 }
			(*it)->startThread(5000); // synch 5 secs
			this->threads.transactionEnd();
			return request->replyResponse(WRET_OK);
		 }
	 }
	this->threads.transactionEnd();
	return request->replyResponse(WRET_ERR_PARAM, "Thread not found");
 }

Response* ThreadManager::mmDoStopThread( const Request* request ) {
	if ( request == NULL ) return NULL;
	long tid = 0;
	string name = "";
	if ( request->getArgument().isNumeric() ) {
		tid = request->getArgument().toLong(0);
		Log(LOG_VERBOSE, ":mmDoStopThread(%d)", tid );
	 }
	else if ( request->getArgument().isStringNotEmpty() ) {
		name = request->getArgument().toString();
		Log(LOG_VERBOSE, ":mmDoStopThread(%s)", name.c_str() );
	 }
	else
		return request->replyResponse(WRET_ERR_PARAM, "name or id expected");

	this->threads.transactionBeginRead();
	tThreadList::ConstIterator it;
	const tThreadList::ConstIterator it_end = this->threads.end();
	for ( it=this->threads.begin(); it!=it_end; ++it ) {
		if ( *it == NULL ) continue;
		if ( (*it)->getThreadID() == tid || (*it)->getThreadName() == name ) {
			if ( !(*it)->isThreadRunning() ) {
				this->threads.transactionEnd();
				return request->replyResponse(WRET_ERR_ILLEGAL_USE, "Not Running!");
			 }
			(*it)->quitThread();
			this->threads.transactionEnd();
			return request->replyResponse(WRET_OK);
		 }
	 }
	this->threads.transactionEnd();
	return request->replyResponse(WRET_ERR_PARAM, "Thread not found");
 }

Response* ThreadManager::mmDoTerminateThread( const Request* request ) {
	if ( request == NULL ) return NULL;
	long tid = 0;
	string name = "";
	if ( request->getArgument().isNumeric() ) {
		tid = request->getArgument().toLong(0);
		Log(LOG_VERBOSE, ":mmDoTerminateThread(%d)", tid );
	 }
	else if ( request->getArgument().isStringNotEmpty() ) {
		name = request->getArgument().toString();
		Log(LOG_VERBOSE, ":mmDoTerminateThread(%s)", name.c_str() );
	 }
	else
		return request->replyResponse(WRET_ERR_PARAM, "name or id expected");

	this->threads.transactionBeginRead();
	tThreadList::ConstIterator it;
	const tThreadList::ConstIterator it_end = this->threads.end();
	for ( it=this->threads.begin(); it!=it_end; ++it ) {
		if ( *it == NULL ) continue;
		if ( (*it)->getThreadID() == tid || (*it)->getThreadName() == name ) {
			(*it)->terminateThread();
			this->threads.transactionEnd();
			return request->replyResponse(WRET_OK);
		 }
	 }
	this->threads.transactionEnd();
	return request->replyResponse(WRET_ERR_PARAM, "Thread not found");
 }

///////////////////////////////////////////////////////////////////////////////////////////////////// METHODS
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

}; // namespace wosh


/*
http://procps.sourceforge.net/
Is the source of ps and other process tools. They do indeed use proc (indicating it is probably the conventional and best way to read process information). Their source is quite readable. The file
/procps-3.2.8/proc/readproc.c
You can also link your program to libproc, which sould be available in your repo (or already installed I would say) but you will need the "-dev" variation for the headers and what-not. Using this API you can read process information and status.
You can use the psState() function through libproc to check for things like
*/